package com.dongjiantong.app.controller.quarantine;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongjiantong.biz.enums.ReportType;
import com.dongjiantong.biz.service.EarMarkLifeReadeService;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.model.Response;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.common.web.util.UserUtil;
import com.dongjiantong.openplatform.annotations.OpenBean;
import com.dongjiantong.openplatform.annotations.OpenMethod;
import com.dongjiantong.quarantine.model.DjtButcherReportCerts;
import com.dongjiantong.quarantine.model.DjtButcherReports;
import com.dongjiantong.quarantine.serviceImpl.BreedReportsFileReadService;
import com.dongjiantong.quarantine.serviceImpl.DjtButcherReportCertsReadService;
import com.dongjiantong.quarantine.serviceImpl.DjtButcherReportsReadService;
import com.dongjiantong.quarantine.serviceImpl.DjtButcherReportsWriteService;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by mz on 18/11/17.
 *
 */
@Slf4j
@OpenBean
public class DjtButcherReportsController {

    @Reference(version = "1.0.0")
    private DjtButcherReportsReadService djtButcherReportsReadService;

    @Reference(version = "1.0.0")
    private DjtButcherReportsWriteService djtButcherReportsWriteService;

    @Reference(version = "1.0.0")
    private DjtButcherReportCertsReadService djtButcherReportCertsReadService;

    @Reference(version = "1.0.0")
    private BreedReportsFileReadService breedReportsFileReadService;

    @Reference(version = "1.0.0")
    private EarMarkLifeReadeService earMarkLifeReadeService;


    /**
     * 查询单据详情
     * @param id 主键id
     * @return Response<DjtButcherReports>
     */
    @OpenMethod(
            key = "find.butcher.report.by.id",
            paramNames = {"id"},
            httpMethods = RequestMethod.GET
    )
    public Response<DjtButcherReports> findById(Long id){

        if(id == null){
            throw new OPServerException(HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getCode(),HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getMessage());
        }

        try{
            DjtButcherReports djtButcherReports = djtButcherReportsReadService.findById(id);
            Map<String , Object> map = Maps.newHashMap();
            map.put("field","quarantine_cert_photo_list");
            map.put("type1", ReportType.SLAUGHTER_QUARANTINE.value());
            map.put("type2",1);
            map.put("relevanceId",id);
            List<String> quarantine_cert_photo_list = breedReportsFileReadService.findListByType(map);
            map.clear();
            map.put("reportId",id);
            map.put("reportType",ReportType.SLAUGHTER_QUARANTINE.value());
            List<String> ear_tag_numbers = earMarkLifeReadeService.findListByBreedReportId(map);
            djtButcherReports.setQuarantine_cert_photo_list(quarantine_cert_photo_list);
            djtButcherReports.setEar_tag_numbers(ear_tag_numbers);
            return Response.ok(djtButcherReports);
        }catch (Exception e){
            log.error(e.getMessage());
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }

    }

    /**
     * 屠宰端分页查询
     * @param pageNum 页码
     * @param pageSize 每页多少条
     * @param butcherFarmId 屠宰场ID
     * @param statuses 状态集合
     * @return Response<PageInfo<DjtButcherReports>>
     */
    @OpenMethod(
            key = "paging.butcher.report.for.butcher",
            paramNames = {"pageNum","pageSize","butcherFarmId","statuses"},
            httpMethods = RequestMethod.GET
    )
    public Response<PageInfo<DjtButcherReports>> pagingForButcher(Integer pageNum ,
                                                                  Integer pageSize ,
                                                                  Long butcherFarmId ,
                                                                  List<Integer> statuses){
        if(butcherFarmId == null){
            throw new OPServerException(HttpCode.BUTCHER_FARM_ID_IS_NOT_EXIST.getCode(),HttpCode.BUTCHER_FARM_ID_IS_NOT_EXIST.getMessage());
        }
        Map<String , Object> map = Maps.newHashMap();
        map.put("butcherFarmId",butcherFarmId);
        if(statuses != null && !statuses.isEmpty()) map.put("statuses",statuses);
        map.put("deleteFlag",1);
        try{
            PageInfo<DjtButcherReports> butcherReportsPageInfo = djtButcherReportsReadService.pagingForButcher(pageNum,pageSize,map);
            return Response.ok(butcherReportsPageInfo);
        }catch (Exception e){
            log.error(e.getMessage());
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 政府端分页查询
     * @param pageNum 页码
     * @param pageSize 每页多少条
     * @param butcherFarmId 屠宰场id
     * @param statuses 状态集合
     * @param fromDate 从时间
     * @param toDate 到时间
     * @return Response<PageInfo<DjtButcherReports>>
     */
    @OpenMethod(
            key = "paging.butcher.report.for.gov",
            paramNames = {"pageNum","pageSize","butcherFarmId","statuses","fromDate","toDate"},
            httpMethods = RequestMethod.GET
    )
    public Response<PageInfo<DjtButcherReports>> pagingForGOV(Integer pageNum,
                                                              Integer pageSize,
                                                              Long butcherFarmId,
                                                              List<Long> statuses,
                                                              String fromDate,
                                                              String toDate){
        Date start = Strings.isNullOrEmpty(fromDate) ? null : DateTime.parse(fromDate).toDate();
        Date end = Strings.isNullOrEmpty(toDate) ? null : DateTime.parse(toDate).toDate();
        Map<String , Object> map = Maps.newHashMap();
        List<Long> butcherFarmIds = new ArrayList<Long>();
        if(butcherFarmId != null) {
            butcherFarmIds.add(butcherFarmId);
        }else {
            LoginInfo loginInfo = UserUtil.getCurrentUser();
            butcherFarmIds = loginInfo.getButcherFactoryIds();
        }
        map.put("butcherFarmIds",butcherFarmIds);
        map.put("deleteFlag",1);
        if(start != null) map.put("start",start);
        if(end != null) map.put("end",end);
        if(statuses != null && !statuses.isEmpty()) map.put("statuses",statuses);
        try{
            PageInfo<DjtButcherReports> butcherReportsPageInfo = djtButcherReportsReadService.pagingForGOV(pageNum,pageSize,map);
            return Response.ok(butcherReportsPageInfo);
        }catch (Exception e){
            log.error(e.getMessage());
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }


    /**
     * 新建一条单据
     * @param djtButcherReports 单据对象
     * @param toStatus 到状态
     * @return Response<Map<String , Object>>
     */
    @Transactional
    @OpenMethod(
            key = "create.butcher.report",
            paramNames = {"djtButcherReports","toStatus"},
            httpMethods = RequestMethod.POST
    )
    public Response<Map<String , Object>> create(DjtButcherReports djtButcherReports ,
                                 Integer toStatus){

        try{
            Date date = new Date();
            LoginInfo loginInfo = UserUtil.getCurrentUser();
            djtButcherReports.setCreated_at(date);
            djtButcherReports.setUpdated_at(date);
            djtButcherReports.setDelete_flag(1);
            return Response.ok(djtButcherReportsWriteService.create(djtButcherReports,toStatus,loginInfo));
        }catch (Exception e){
            log.error(e.getMessage());
            return Response.fail(HttpCode.DATA_CREATE_FAIL.getCode(),HttpCode.DATA_CREATE_FAIL.getMessage());
        }
    }

    /**
     * 更新一条单据
     * @param djtButcherReports 单据对象
     * @param toStatus 到状态
     * @return Response<Map<String , Object>>
     */
    @Transactional
    @OpenMethod(
            key = "update.butcher.report",
            paramNames = {"djtButcherReports","toStatus"},
            httpMethods = RequestMethod.POST
    )
    public Response<Map<String , Object>> update(DjtButcherReports djtButcherReports ,
                                                 Integer toStatus){

        if(djtButcherReports.getId() == null){
            throw new OPServerException(HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getCode(),HttpCode.PRIMARY_KEY_ID_IS_NOT_EXIST.getMessage());
        }
        try{
            Date date = new Date();
            djtButcherReports.setUpdated_at(date);
            djtButcherReports.setDelete_flag(1);
            LoginInfo loginInfo = UserUtil.getCurrentUser();
            Integer status = djtButcherReportsReadService.findStatusById(djtButcherReports.getId());
            if(status != null && !status.equals(djtButcherReports.getStatus())){
                throw new OPServerException(HttpCode.DOCUMENT_REPEAT_SUBMIT.getCode(),HttpCode.DOCUMENT_REPEAT_SUBMIT.getMessage());
            }
            Map<String , Object> resultMap = djtButcherReportsWriteService.update(djtButcherReports,toStatus,loginInfo);
            return Response.ok(resultMap);
        }catch (Exception e){
            log.error(e.getMessage());
            return Response.fail(HttpCode.DATA_UPDATE_FAIL.getCode(),HttpCode.DATA_UPDATE_FAIL.getMessage());
        }
    }


    /**
     * 查询屠宰检疫的发证数量
     * @param reportId 屠宰检疫的id
     * @return Response<Long>
     */
    @OpenMethod(
            key = "count.butcher.report.cert.by.report.id",
            paramNames = {"reportId"},
            httpMethods = RequestMethod.GET
    )
    public Response<Long> countByReportId(Long reportId){
        if(reportId == null){
            throw new OPServerException(HttpCode.PRIMARY_PARAM_IS_NULL.getCode(),HttpCode.PRIMARY_PARAM_IS_NULL.getMessage());
        }
        Map<String , Object> map = Maps.newHashMap();
        map.put("reportId",reportId);
        map.put("status",1);
        try{
            Long count = djtButcherReportCertsReadService.countByReportId(map);
            return Response.ok(count);
        }catch (Exception e){
            log.error(e.getMessage());
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    /**
     * 分页查询屠宰检疫的证
     * @param pageNum 页码
     * @param pageSize 每页条数
     * @param reportId 屠宰检疫的单据id
     * @return Response<PageInfo<DjtButcherReportCerts>>
     */
    @OpenMethod(
            key = "paging.butcher.report.by.report.id",
            paramNames = {"pageNum","pageSize","reportId"},
            httpMethods = RequestMethod.GET
    )
    public Response<PageInfo<DjtButcherReportCerts>> paging(Integer pageNum,
                                                            Integer pageSize,
                                                            Long reportId){
        if(reportId == null){
            throw new OPServerException(HttpCode.PRIMARY_PARAM_IS_NULL.getCode(),HttpCode.PRIMARY_PARAM_IS_NULL.getMessage());
        }
        Map<String , Object> map = Maps.newHashMap();
        map.put("reportId",reportId);
        map.put("status",1);
        try{
            PageInfo<DjtButcherReportCerts> pageInfo = djtButcherReportCertsReadService.paging(pageNum,pageSize,map);
            return Response.ok(pageInfo);
        }catch (Exception e){
            log.error(e.getMessage());
            return Response.fail(HttpCode.INTERNAL_SERVER_ERROR.getCode(),HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }
}
